<?php
namespace app\index\controller;
use app\index\Controller\Base;
use think\Db;
class Index extends Base
{
    public function index()
    {
    	$this->assign('new_date',date('Y-m-d'));
		$this->assign('day_date',date('Y-m-d',strtotime("+1 day")));
       	return $this->fetch();
    }
	public function ctyd()
    {
		$this->assign('btype',get_brower_type());
		//餐厅列表
		if($_POST){
			$longitude = input('longitude');
			$latitude = input('latitude');
			$page=1; 
			if(input("page")){
				$page=input("page");
			} 
			
			$begin=($page-1)*10;
			$order = ' order by juli asc '; 
			
			$limit = " limit $begin,10 "; 
			$field='id,thumb,store_name,store_address,longitude,latitude,ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli ';
			$sql = 'select '.$field.' from hyjt_store '.$order.$limit;
			$resultList=Db::query($sql); 
			return json(["list"=>$resultList]);
		}
       	return $this->fetch();
    }
	//订餐预约
	public function yuyue()
    {
    	$user_id = session('user_info')['id']; 
    	if($_POST){ 
    		//预定信息
			$res2 = restaurant_log($user_id,$_POST['data']['store_id'],$_POST['data']['room_num'],$_POST['data']['dd_time'],2,$_POST['data']['message'],$_POST['data']['jc_time'],$_POST['data']['is_rooms'],0);

			if($res2){
				return $this->success('预约成功'); 
			}else{
				return $this->error('预约失败');
			}
    	}
    	$this->assign('store_id',input('store_id'));
       	return $this->fetch();
    }
	/**
	 * 酒店分类
	 * */
	public function house_list()
    {
    	//查询指定酒店下面的分类
    	$store_id = input('id');
		$sort_list = db('room_sort')->alias('a')->join('store b','a.store_id=b.id','LEFT')->field('a.*,b.store_address,b.store_phonenumber,b.store_name,b.thumb')->where('a.store_id',$store_id)->select();
		
		$sort =db('store')->where('id',$store_id)->find();
		$this->assign('sort',$sort);
		$this->assign('sort_list',$sort_list);
       	$this->assign('start_time',input('start_time'));
		$this->assign('end_time',input('end_time'));
		$days = floor((strtotime(input('end_time'))-strtotime(input('start_time')))/86400);
		$this->assign('days',$days);
		return $this->fetch();
    }
	/**
	 * 就餐预约
	 * */
	public function hotel_yy(){
       	return $this->fetch();
    }
	/**
	 * 查询酒店信息
	 * */
	public function hotel_list()
	{
		$this->assign('start_time',input('start_time'));
		$this->assign('end_time',input('end_time'));
		$hotel_list = db('store')->select();
		$this->assign('hotel_list',$hotel_list);
		return $this->fetch();
	}
	
	/**
	 * 订房预约
	 * */
	public function room_pre()
    {
    	$user_id = session('user_info')['id'];
    	$user_info = db('user')->alias('a')->join('userlevel b','a.level_id=b.id','LEFT')->where('a.id',$user_id)->field('a.level_id,a.kq_hx,a.balance,a.mobile,a.user_name,b.name as level_name,b.discount,b.zs_num')->find();
    	$id = input('id');
		$list = db('room_sort')->alias('a')->join('store b','a.store_id=b.id','LEFT')->field('a.*,b.store_address,b.store_phonenumber,b.store_name,a.room_num')->where('a.id',$id)->find();
		//折扣
		$discount = 0;
		if($user_info['level_id']>0){
			$discount=db("storediscount")->where(["store_name_id"=>$list['store_id'],'userlevel'=>$user_info['level_id']])->value('discount');
		}
		$user_info['discount'] = $discount;
		$this->assign('list',$list);
		$this->assign('start_time',input('start_time'));
		$this->assign('end_time',input('end_time'));
		$days = floor((strtotime(input('end_time'))-strtotime(input('start_time')))/86400);
		$this->assign('days',$days);
		$this->assign('user_info',$user_info);
       	return $this->fetch();
    }
	
	/**
	 * 房间预约提交订单
	 * 
	 * */
	public function room_order(){
		if($_POST){
			$user_id = session('user_info')['id'];
	    	$user_info = db('user')->alias('a')->join('userlevel b','a.level_id=b.id','LEFT')->where('a.id',$user_id)->field('a.balance,a.level_id,a.id,a.mobile,a.user_name,b.name as level_name,b.discount')->find();
			$room = db('room_sort')->where('id',$_POST['room_id'])->find();
			if($_POST['room_num']>$room['room_num']){
				return json(['code'=>400,"msg"=>"目前最多可预定".$room['room_num'].'间房']);
			}
			$discount = $_POST['discount']?$_POST['discount']:0;
			$zk = $discount/100;//折扣
			$days = floor((strtotime($_POST['end_time'])-strtotime($_POST['start_time']))/86400);
			$origin_price = $room['room_price']*$_POST['room_num']*$days;//应付金额
			$balance = $room['room_price']*$_POST['room_num']*$days;  //实际支付
			$yh_money = $origin_price-$balance; //优惠金额
			
			$is_hx=0;
			if($_POST['zf_type']==6){//房券支付
				$is_hx=0;  
				$u_where['a.user_id'] = $user_id;
				$u_where['b.id'] = $_POST['room_id'];
				$u_where['a.start_time'] = array('elt',date('Y-m-d',time()));
				$u_where['a.end_time'] = array('egt',date('Y-m-d',time()));
				$u_where['a.num'] = array('gt',0);
				$userhouse = db('userhouse')->alias('a')->join('room_sort b','a.house_id=b.id')->field('a.*')->where($u_where)->find();
				if(!$userhouse){
					return json(['code'=>400,"msg"=>"暂无该房间房券"]);
				}
				if($userhouse['num']<$_POST['room_num']){
					return json(['code'=>400,"msg"=>"目前房券只能预定".$userhouse['num'].'间']);
				}
			}elseif($_POST['zf_type']==5){//会员卡支付
			    //有会员卡的时候才可以享受折扣
			    if($user_info['level_id'] != 0){
			    	$balance = ($room['room_price']-$room['room_price']*$zk)*$_POST['room_num']*$days;  //实际支付
			        $yh_money = $origin_price-$balance; //优惠金额
			    }
			   
				if($balance>$user_info['balance']){
					return json(['code'=>400,"msg"=>'会员卡余额不足']);
				}
			}
			$result = true;
			Db::startTrans();
			//订单信息
			$order_sn = order_create_no();
			$res=reserve_pay_log($room['store_id'],$user_info['id'],$balance,3,$order_sn,$_POST['zf_type'],'客房预定',1,$user_info['level_id'],$origin_price,$room['id']);
			if(!$res){$result=false;}
			$order_id = db('paylog')->getLastInsID();
			//预定信息
			$res2 = reserve_log($user_id,$room['store_id'],$room['id'],$_POST['start_time'],$_POST['end_time'],$_POST['room_num'],$_POST['ids_num'],$_POST['dd_time'],$order_id,$_POST['zf_type'],$origin_price,$balance,$is_hx,$days);
			if(!$res2){$result=false;}
			
			if ($result==false){
				Db::rollback();
				return json(['code'=>400,"msg"=>'预定失败']);
			}else {
			    Db::commit();
				if($_POST['zf_type']==2){//微信支付
					$url=pay_code('H506','98525211960f75494838aa9dde12af3f','600fbbf2d114ebbd04fdd0f9bec22eb8',$balance,2,$order_sn);
					return json(['code'=>202,"url"=>$url,"msg"=>'']);
				}elseif($_POST['zf_type']==5){//会员卡支付
					$this->card_pay($order_sn);
				}elseif($_POST['zf_type']==6){//房券支付
					$this->hounse_pay($userhouse['id'],$order_sn);
				}
				return json(['code'=>200,"msg"=>'预定成功']);
			}
		}
		
	}
	
	/**
     * 获取验证码
     * 注意防盗刷
     * 
     */
    public function verify_code(){
    	if(request()->isPost()){
    		return get_code($_POST['mobile'],1);
    	}
    }
	
	//用户绑定
	public function phone()
	{
		if(request()->isPost()){
    		//验证验证码是否错误，过期
			$result = check_sendcode($_POST['mobile'], $_POST['yzm'], '发送成功'); 
			if($result != 1) {
				return json(['code'=>400,"msg"=>'验证码错误或过期']);
			} 
			$user_id = session('user_info')['id'];
			$data['user_name'] = $_POST['user_name'];
			$data['mobile'] = $_POST['mobile'];
			//判断该号码是否绑定过
			$info = db('user')->where('mobile',$_POST['mobile'])->find();
			if($info){
				return json(['code'=>400,"msg"=>'该号码已经绑定过']);
			}
			$res = db('user')->where('id',$user_id)->update($data);
			if($res){
				session("user_info",$info);
				return json(['code'=>200,"msg"=>'绑定成功']);
			}else{
				return json(['code'=>400,"msg"=>'绑定失败']);
			}
    	}
	}
	
	
	//模拟回调
	public function text_pay(){
		$pay = new Payment();
		$pay->callback();
	}
	
	/**
	 * 客房预订会员卡支付
	 * $order_sn 订单号
	 * */
	public function card_pay($order_sn){
		$paylog = db('paylog')->where('order_sn',$order_sn)->find();
		Db::startTrans();
		$res=[];
		$room_num = db('reserve')->where('order_id',$paylog['id'])->value('room_num');
		$res[]= db('room_sort')->where('id',$paylog['room_id'])->setDec('room_num',$room_num);
		$res[]=db('user')->where('id',$paylog['user_id'])->setDec('balance',$paylog['balance']);  //更新用户表
		$res[]=db('reserve')->where('order_id',$paylog['id'])->update(['state'=>2,'pay_time'=>now_time()]);  //更新预定表
		$res[]=db('paylog')->where('id',$paylog['id'])->update(['state'=>2,'pay_time'=>now_time()]);//更新支付表
		$res[]=consume_log($paylog['order_sn'],$paylog['user_id'],0,$paylog['balance'],$paylog['level_id'],$paylog['pay_type'],0,now_time(),2,0,'客房预订会员卡支付');//客房预订消费
		if (in_array(false, $res)){
		    Db::rollback();
		}else {
		    Db::commit();
		}
	}
	
	/**
	 * 房券支付预定
	 * $uh_id  用户房券客房关系表ID
	 * */
	public function hounse_pay($uh_id,$order_sn){
		//1.房券核销记录
		//2.更新用户表
		$paylog = db('paylog')->where('order_sn',$order_sn)->find();
		Db::startTrans();
		$res=[];
		$room_num = db('reserve')->where('order_id',$paylog['id'])->value('room_num');
		$res[]= db('room_sort')->where('id',$paylog['room_id'])->setDec('room_num',$room_num);  //减去房间
		$res[]=db('reserve')->where('order_id',$paylog['id'])->update(['state'=>2,'pay_time'=>now_time()]);  //更新预定表
		$res[]=db('paylog')->where('id',$paylog['id'])->update(['state'=>2,'pay_time'=>now_time()]);//更新支付表
//		$res[]=consume_log($paylog['order_sn'],$paylog['user_id'],0,$paylog['balance'],$paylog['level_id'],$paylog['pay_type'],0,now_time(),4,0,'房券预定',$uh_id);//房券核销
		$res[]=db('userhouse')->where('id',$uh_id)->setDec('num',$room_num); //减去用户房券
		//累加减去用户表里现有总房券
		$res[] = db('user')->where('id',$paylog['user_id'])->setDec('kaquan',$room_num);
		if (in_array(false, $res)){
		    Db::rollback();
		}else {
		    Db::commit();
		}
	} 
}

